Ext.define('DragonApp.view.property.Controller', {

    extend: 'Ext.app.ViewController',
    alias: 'controller.property',

    requires: [
        'DragonApp.util.String',
        'DragonApp.util.Util',
        'DragonApp.util.Msg'
    ],

    //================
    //道具发放类型选择
    //================
    onIssueComboxSelect: function(combo, record, eOpts) {

        var form = Ext.ComponentQuery.query('propertyform')[0];
        var idField = Ext.ComponentQuery.query('textfield[name=id]', form)[0];
        var nicknameField = Ext.ComponentQuery.query('textfield[name=nickname]', form)[0];

        var name = record.get('name');

        if ("全服发放" == name) {

            idField.reset();
            nicknameField.reset();

            idField.setDisabled(true);
            nicknameField.setDisabled(true);

        } else if ("单个发放" == name) {

            idField.setDisabled(false);
            nicknameField.setDisabled(false);
        }
    },

    checkEmpty: function(form) {

        var fields = form.query('textfield');

        for (var i = 0; i < fields.length; i++) {
            var value = fields[i].getValue();
            if ("" != value && null != value) return false;
        }
        return true;
    },

    isEmptyNameIdField: function(formValue) {

        if (1 == formValue.issuetype && "" == (formValue.id).trim() && "" == (formValue.nickname).trim()) {
            DragonApp.util.Msg.showToast("玩家ID字段和玩家名字段均为空");
            return false;
        }

        return formValue;
    },

    previewIssue: function() {
        return true;
    },

    //========
    //道具发放
    //========
    onSubmitClick: function(button, e, options) {

        // 预览内容
        if (!this.previewIssue()) {
            return;
        }
        var me = this;

        // 字段全空判断
        var container = this.getView();

        var propform = Ext.ComponentQuery.query('propertyform')[0];

        if (this.checkEmpty(propform)) {

            propform.query('textfield')[0].focus();
            DragonApp.util.Msg.showToast('请输入正确的信息');
            return;
        }

        form = propform.getForm();

        if (!form.isValid()) return;

        var formValue = form.getValues();
        var res = this.isEmptyNameIdField(formValue);

        //数字签名
        if (false != res) {
            formValue = res;
            formValue = DragonApp.util.Util.addSign(formValue);
        } else {
            return;
        }

        //断点调试
        //DragonApp.util.Object.consoleLogObj(formValue);

        propform.mask('发送中...');

        Ext.data.JsonP.request({
            url: DragonApp.ux.config.Config.getUrl('/index/Issue/issue/'),
            callbackKey: "callback",
            params: formValue,
            async: false,
            scope: me,
            success: function(result) {

                propform.unmask();

                switch (result.success) {
                    case true: //发放成功
            //=======================================
            //curl请求调试
            DragonApp.util.Msg.showToast(result.msg);
            return;
            //=======================================
                        if ("ok" == result.msg.toLowerCase() && 0 == result.code) {
                            DragonApp.util.Msg.showToast("本次邮件发送/道具发放已成功,请查阅发放日志");
                            me.finishIssue();
                        }
                        break;
                    case false: //发放失败
                        DragonApp.util.Msg.showToast(result.msg);
                        break;
                }

            },
            failure: function(result) {
                propform.unmask();
                DragonApp.util.Msg.showToast(result);
            }
        });
    },

    onTextFieldSpecialKey: function(field, e, options) {

        if (e.getKey() === e.ENTER) {
            if (this.getView().getForm().isValid()) {
                this.onSubmitClick();
            }
        }
    },
    //添加、修改道具
    onToggleAttachment: function(btn, pressed) {

        var formPanel = Ext.ComponentQuery.query('propertyform')[0];
        var container = Ext.ComponentQuery.query('attachement')[0];

        formPanel.setCollapsed(true);
        formPanel.hide();
        container.setCollapsed(false);
        container.show();

        btn.setText('道具变更');
    },

    //添加道具
    onAdd: function(button, event) {

        var attachement = Ext.ComponentQuery.query('attachement')[0];
        var grid = Ext.ComponentQuery.query('grid', attachement)[0];

        var rowIndex = button.up('gridview').indexOf(button.el.up('table'));
        var record = grid.getStore().getAt(rowIndex);

        //种类上限提示
        var issueStore = Ext.data.StoreManager.lookup('selected_prop');

        if (issueStore.getCount() >= 5) {

            DragonApp.util.Msg.showToast('发放种类不能大于五种');

        } else {

            //增加记录
            var selectedPropStore = Ext.data.StoreManager.lookup('selected_prop');
            selectedPropStore.add(Ext.create('DragonApp.model.SelectedProp', {
                id: record.get('id'),
                name: record.get('name'),
                num: 1
            }));
        }
    },

    //取消所选
    onCancleSelect: function(button, e) {
        Ext.data.StoreManager.lookup('selected_prop').removeAll();
    },

    //确认所选
    onConfirmSelect: function(button, e) {

        var issueArr = [];
        var issueStore = Ext.data.StoreManager.lookup('selected_prop');

        //邮件及道具
        var formPanel = Ext.ComponentQuery.query('propertyform')[0];
        var container = Ext.ComponentQuery.query('attachement')[0];

        //数量确认
        issueStore.commitChanges();

        //缓存发放内容

        var temp = [];
        var _record;
        for (var i = 0; i < issueStore.getCount(); i++) {

            _record = issueStore.getAt(i);

            var data = {};
            data.id = _record.get('id');
            data.name = _record.get('name');
            data.num = _record.get('num');

            temp.push(data);
        }

        sessionStorage.setItem("issueRecord", JSON.stringify(temp));

        //遍历发放列表

        for (var j = 0; j < issueStore.getCount(); j++) {

            var record = issueStore.getAt(j);

            //深拷贝对象，删除名称
            var obj = DragonApp.util.Util.copyObj(record.data);
            delete obj.name;

            //内容数组增加发放元素
            issueArr.push(obj);
        }

        //最终发放内容字符串
        var issuecontent = Ext.encode(issueArr);

        //将所选道具仓库信息序列赋值
        var issuecontent_field = Ext.ComponentQuery.query('hiddenfield[name="issuecontent"]', formPanel)[0];
        issuecontent_field.setValue(issuecontent);

        //道具数量状态提示
        var propNumField = Ext.ComponentQuery.query('displayfield')[2];
        propNumField.setValue(issueArr.length);

        formPanel.setCollapsed(false);
        formPanel.show();

        container.setCollapsed(true);
        container.hide();
    },

    //发放面板展开
    onFormExpand: function(p, eOpts) {

        var container = Ext.ComponentQuery.query('attachement')[0];
        container.setCollapsed(true);
        container.hide();
    },

    //发放面板折叠
    onFormCollapse: function(p, eOpts) {

        p.hide();
        var container = Ext.ComponentQuery.query('attachement')[0];
        container.setCollapsed(false);
        container.show();
    },

    //添加道具面板展开
    onAttachementExpand: function(p, eOpts) {

        var formPanel = Ext.ComponentQuery.query('propertyform')[0];
        formPanel.setCollapsed(true);
        formPanel.hide();
    },

    //添加道具面板折叠
    onAttachementCollapse: function(p, eOpts) {

        p.hide();
        var formPanel = Ext.ComponentQuery.query('propertyform')[0];
        formPanel.setCollapsed(false);
        formPanel.show();
    },

    //文字区域渲染
    onTextareaChange: function() {

        var textArea = Ext.ComponentQuery.query('textarea', this.getView())[0],
            charCount = Ext.ComponentQuery.query('displayfield')[1],
            parser = new CODE();

        //字符计数
        var v = textArea.getValue();
        var cc = parser.CountCharWithoutStyle(v);

        charCount.setValue(cc);
    },

    //禁用发放按钮
    disableIssueBtn: function() {

        var formPanel = Ext.ComponentQuery.query('propertyform')[0];
        var attachementPanel = Ext.ComponentQuery.query('attachement')[0];

        var previewBtn = formPanel.queryById('previewBtn');
        var issueBtn = formPanel.queryById('submitBtn');
        var resetBtn = formPanel.queryById('resetBtn');
        var addBtn = formPanel.queryById('addBtn');

        addBtn.setDisabled(true);
        resetBtn.setDisabled(true);
        issueBtn.setDisabled(true);
        previewBtn.setDisabled(true);

        attachementPanel.hide();
    },

    //禁用发放按钮
    finishIssue: function() {
        var selectedPropStore = Ext.data.StoreManager.lookup('selected_prop');
        selectedPropStore.removeAll();
        sessionStorage.removeItem("issueRecord");
        this.disableIssueBtn();
    }
});